package com.weiqiao.report.distributior.Service.impl;

import com.google.gson.Gson;
import com.mingsoft.util.StringUtil;
import com.weiqiao.report.distributior.Service.DistributionStatisticsService;
import com.weiqiao.report.distributior.domain.DistributionStatisticsEntity;
import com.weiqiao.report.distributior.domain.ReturnDistributionStatisticsEntity;
import com.weiqiao.report.distributior.domain.dto.UserReportEntityDTO;
import com.weiqiao.report.distributior.repository.DistributionStatisticsRepository;
import com.weiqiao.report.distributior.repository.IUserRepository;
import com.weiqiao.utils.DateUtil;
import com.weiqiao.utils.PageUtil;
import com.weiqiao.utils.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
* @author PEI
* @date 2020-08-10
*/
@Service("DistributionStatisticsServiceImpl")
public class DistributionStatisticsServiceImpl implements DistributionStatisticsService {

    /**
     * 统计数据层
     */
    @Autowired
    private DistributionStatisticsRepository distributionstatisticsRepository;

    /**
     * 用户数据层
     */
    @Autowired
    private IUserRepository userRepository;

    @Override
    public ReturnDistributionStatisticsEntity statisticsResultList(int company_id, Bson filter, int page, int limit) {
        ReturnDistributionStatisticsEntity entity = new ReturnDistributionStatisticsEntity();
        int count = 0;
        List<DistributionStatisticsEntity> list = new ArrayList<>();
        List<Document> docList = new ArrayList<>();
        // 查询条件
        Document match = new Document("$match", filter);
        docList.add(match);
        // 字串拼接，输出内容聚合管道数据汇总
        Document r = new Document("_id",new Document("user_id","$user_id"));
        r.append("user_id", new Document("$last", "$user_id"));
        r.append("create_date", new Document("$last", "$create_date"));
        r.append("lower_level_invitation", new Document("$sum", "$lower_level_invitation"));
        r.append("own_invitation", new Document("$sum", "$own_invitation"));
        r.append("own_apply", new Document("$sum", "$own_apply"));
        r.append("invitation_income", new Document("$sum", "$invitation_income"));
        Document group = new Document("$group", r);
        docList.add(group);
        Document sort = new Document("$sort", new Document("invitation_income", -1));
        docList.add(sort);
        List<String> array = distributionstatisticsRepository.statisticsList(company_id, docList);
        // 所取数据不为空,在后台做分页返回
        if (CollectionUtils.isNotEmpty(array)) {
            count = array.size();
            // 所取数据不能大于集合的总数
            int skip = page * limit;
            if (skip > count) {
                // 上一页的末端位置
                skip = count - ((page - 1) * limit) -limit;
                // 所取条数
                limit = count -skip;
            }
            // 当前页之和大于总数，count = skip + limit
            if ((skip + limit) > count) {
                limit = count - skip;
            }
            // 末尾下标
            limit = skip + limit;
            if (limit > 0) {
                // 截取数据，且进行内容填充
                List<String> newList =  array.subList(skip, limit);
                this.getListToEntity(company_id, newList, list);
            }
        }
        entity.setCount(count);
        entity.setList(list);
        return entity;
    }

    /**
     * 转实体类
     * @param array 统计数据
     * @param list 返回的集合
     */
    private void getListToEntity(int companyId, List<String> array, List<DistributionStatisticsEntity> list) {
        Gson gson = new Gson();
        for (String info: array) {
            DistributionStatisticsEntity entity = gson.fromJson(info, DistributionStatisticsEntity.class);
            Bson filter = new Document("user_id", entity.getUser_id());
            String user = userRepository.getOne(companyId, filter);
            if (!StringUtil.isBlank(user)) {
                // 基础信息完善
                UserReportEntityDTO userEntity = gson.fromJson(user, UserReportEntityDTO.class);
                entity.setTeam_id(userEntity.getTeam_id());
                entity.setMember_type(userEntity.getMember_type());
                entity.setInvite_id(userEntity.getRecommend_id());
                entity.setPhone(userEntity.getPhone());
                entity.setName(userEntity.getUser_name());
                entity.setNick_name(userEntity.getNickname());
                entity.setScore(userEntity.getScore());
            }
            if (StringUtil.isLong(entity.getCreate_date())) {
                // 时间转换
                entity.setCreate_date(DateUtil.timestampToString(entity.getCreate_date()));
            }
            list.add(entity);
        }
    }

    @Override
    public int countNum(int company_id, Bson filter) {
        int count = distributionstatisticsRepository.countNum(company_id, filter);
        return count;
    }

    @Override
    public List<DistributionStatisticsEntity> findList(int company_id, Bson filter, Pageable pageable) {
        List<String> array = distributionstatisticsRepository.getList(company_id, filter, pageable);
        List<DistributionStatisticsEntity> list = new ArrayList<>();
        if (CollectionUtils.isEmpty(array)) {
            return list;
        }
        for (String info : array) {
            DistributionStatisticsEntity entity = new Gson().fromJson(info, DistributionStatisticsEntity.class);
            list.add(entity);
        }
        return list;
    }

    @Override
    public DistributionStatisticsEntity getEntity(int companyId, Bson filter) {
        String info = distributionstatisticsRepository.getOne(companyId, filter);
        if (StringUtils.isBlank(info)) return new DistributionStatisticsEntity();
        return new Gson().fromJson(info, DistributionStatisticsEntity.class);
    }


    @Override
    public boolean addInfo(int company_id, String json) {
    return distributionstatisticsRepository.addInfo(company_id, json);
    }

    @Override
    public boolean updateInfo(int company_id, Bson filter, Document doc) {
    return distributionstatisticsRepository.updateInfo(company_id, filter, doc);
    }
}